<template>
  <div class="page-content">
    <table-bar
      :showTop="false"
      @search="search"
      @reset="resetForm(searchFormRef)"
      @changeColumn="changeColumn"
      :columns="columns"
    >
      <template #top>
        <el-form :model="searchForm" ref="searchFormRef" label-width="82px">
          <el-row :gutter="20">
            <form-input label="文档名" prop="name" v-model="searchForm.name" />
            <form-select
              label="文档状态"
              prop="status"
              v-model="searchForm.status"
              :options="statusOptions"
            />
          </el-row>
        </el-form>
      </template>
      <template #bottom>
        <el-button type="primary" v-ripple @click="openUploadDialog">上传文档</el-button>
      </template>
    </table-bar>

    <art-table
      :data="tableData"
      selection
      :currentPage="currentPage"
      :pageSize="pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
      <template #default>
        <el-table-column
          label="文档名"
          prop="fileName"
          #default="scope"
          width="300px"
          v-if="columns[0].show"
        >
          <div class="document" style="display: flex; align-items: center">
            <img class="doc-icon" :src="getDocumentIcon(scope.row.fileName)" />
            <div>
              <p class="doc-name" @click="previewDocument(scope.row)">{{ scope.row.fileName }}</p>
            </div>
          </div>
        </el-table-column>
        <el-table-column label="状态" prop="status" #default="scope" v-if="columns[1].show">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" sortable v-if="columns[2].show">
          <template #default="scope">
            <div class="time-column">
              <div class="date">{{ formatDate(scope.row.createTime) }}</div>
              <div class="time">{{ formatTime(scope.row.createTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" sortable v-if="columns[3].show">
          <template #default="scope">
            <div class="time-column">
              <div class="date">{{ formatDate(scope.row.updateTime) }}</div>
              <div class="time">{{ formatTime(scope.row.updateTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px">
          <template #default="scope">
            <button-table type="download" @click="downloadDocument(scope.row)" />
            <el-dropdown trigger="click">
              <button-table type="more" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="deleteDocument(scope.row)">
                    <el-icon style=" margin-right: 5px;color: #f56c6c"><Delete /></el-icon>删除文档
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="previewDialogVisible"
      title="文档预览"
      width="80%"
      :before-close="handleClosePreview"
    >
      <div class="document-preview">
        <iframe
          v-if="currentDocument && currentDocument.previewUrl"
          :src="currentDocument.previewUrl"
          width="100%"
          height="600px"
        ></iframe>
        <div v-else class="no-preview">
          <el-icon><WarningFilled /></el-icon>
          <p>该文档暂不支持预览，请下载后查看</p>
        </div>
      </div>
    </el-dialog>

    <!-- 添加上传文档对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="600px"
      :before-close="handleCloseUpload"
    >
      <div class="upload-container">
        <div class="upload-form">
          <div class="form-item">
            <span class="required-label">文件：</span>
            <el-upload
              class="upload-area"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileChange"
              :before-upload="beforeUpload"
              :file-list="fileList"
              :accept="fileType"
              multiple
            >
              <div class="upload-content">
                <el-icon class="upload-icon"><Document /></el-icon>
                <div class="upload-text">
                  <p>单文件最大不超过{{ MAX_FILE_SIZE_MB }}M</p>
                  <p>支持多选，单击或拖动文件到此区域进行上传</p>
                </div>
              </div>
            </el-upload>
          </div>

          <div class="form-item">
            <span class="required-label">文件类型：</span>
            <el-radio-group v-model="fileType">
              <el-radio label=".docx,.pdf,.md,.txt">文档文件(.docx,.pdf,.md,.txt)</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseUpload">取消</el-button>
          <el-button type="primary" @click="submitUpload">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { WarningFilled, Delete, Document } from '@element-plus/icons-vue'

  // 定义自定义文档接口
  interface DocumentItem {
    id: string
    fileName: string
    uploader: string
    status: string
    createTime: string
    updateTime: string
    previewUrl: string | null
  }

  // 状态常量定义
  const STATUS = {
    UPLOADING: '0',
    UPLOAD_SUCCESS: '1',
    GENERATING: '2',
    GENERATE_SUCCESS: '3',
    UPLOAD_FAILED: '4',
    GENERATE_FAILED: '5'
  }

  // 文件上传配置
  const MAX_FILE_SIZE_MB = 50

  // 首先声明所有需要的变量和常量
  const previewDialogVisible = ref(false)
  const currentDocument = ref<DocumentItem | null>(null)
  const fileList = ref<any[]>([])
  const columns = reactive([
    { name: '文档名', show: true },
    { name: '状态', show: true },
    { name: '创建时间', show: true },
    { name: '更新时间', show: true }
  ])
  const searchFormRef = ref<FormInstance>()
  const searchForm = reactive({
    name: '',
    status: ''
  })
  const statusOptions = [
    { value: STATUS.UPLOADING, label: '上传中' },
    { value: STATUS.UPLOAD_SUCCESS, label: '上传成功' },
    { value: STATUS.GENERATING, label: '测试集生成中' },
    { value: STATUS.GENERATE_SUCCESS, label: '测试集生成成功' },
    { value: STATUS.UPLOAD_FAILED, label: '上传失败' },
    { value: STATUS.GENERATE_FAILED, label: '测试集生成失败' }
  ]
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const uploadDialogVisible = ref(false)
  const fileType = ref<string>('.docx,.pdf,.md,.txt')

  // 初始化数据
  const allDocuments = ref<DocumentItem[]>([])
  const filteredDocuments = ref<DocumentItem[]>([])

  // 在组件挂载时加载数据
  onMounted(() => {
    loadDocuments()
  })

  // 加载文档数据
  const loadDocuments = () => {
    allDocuments.value = generateMockData()
    filteredDocuments.value = [...allDocuments.value]
    total.value = allDocuments.value.length
  }

  // 格式化日期时间函数
  const formatDateTime = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 生成模拟数据
  const generateMockData = () => {
    const result = []
    const fileTypes = [
      { ext: 'docx', name: '需求文档' },
      { ext: 'pdf', name: '项目计划' },
      { ext: 'md', name: '接口文档' },
      { ext: 'txt', name: '会议记录' }
    ]
    const uploaders = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']

    for (let i = 1; i <= 10; i++) {
      const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)]
      const status = Object.values(STATUS)[Math.floor(Math.random() * Object.values(STATUS).length)]
      const uploader = uploaders[Math.floor(Math.random() * uploaders.length)]

      // 生成随机日期（过去两年内）
      const createDate = new Date()
      createDate.setDate(createDate.getDate() - Math.floor(Math.random() * 730))
      const createTime = formatDateTime(createDate)

      // 更新时间在创建时间之后
      const updateDate = new Date(createDate)
      updateDate.setDate(updateDate.getDate() + Math.floor(Math.random() * 30))
      const updateTime = formatDateTime(updateDate)

      result.push({
        id: i.toString(),
        fileName: `${fileType.name}_${i}.${fileType.ext}`,
        uploader: uploader,
        status: status,
        createTime: createTime,
        updateTime: updateTime,
        previewUrl: Math.random() > 0.3 ? `https://example.com/preview/doc${i}` : null
      })
    }

    return result
  }

  // 清除文件列表
  const clearFileList = () => {
    fileList.value = []
  }

  interface UploadFile {
    name: string
    size: number
    [key: string]: any
  }

  // 文件变更处理函数
  const handleFileChange = (uploadFile: any, uploadFiles: any[]) => {
    fileList.value =
      uploadFile.status === 'removed'
        ? uploadFiles.filter((file) => file.uid !== uploadFile.uid)
        : uploadFiles
  }

  // 上传前验证
  const beforeUpload = (file: any) => {
    const extension = file.name.split('.').pop()?.toLowerCase() || ''
    const allowedExtensions = fileType.value.split(',').map((ext) => ext.trim().replace('.', ''))
    const isValidType = allowedExtensions.includes(extension)
    const isLt3M = file.size / 1024 / 1024 < MAX_FILE_SIZE_MB

    if (!isValidType) {
      ElMessage.error(`文件 "${file.name}" 类型不支持! 请上传 ${fileType.value} 格式的文件`)
      return false
    }
    if (!isLt3M) {
      ElMessage.error(`文件 "${file.name}" 大小超过 ${MAX_FILE_SIZE_MB}MB 限制!`)
      return false
    }

    return true
  }

  // 搜索函数
  const search = () => {
    filteredDocuments.value = allDocuments.value.filter((doc) => {
      const nameMatch =
        !searchForm.name || doc.fileName.toLowerCase().includes(searchForm.name.toLowerCase())
      const statusMatch = !searchForm.status || doc.status === searchForm.status
      return nameMatch && statusMatch
    })

    total.value = filteredDocuments.value.length
    currentPage.value = 1

    ElMessage.success('搜索完成')
  }

  // 重置搜索表单
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()

    filteredDocuments.value = allDocuments.value
    total.value = allDocuments.value.length
    currentPage.value = 1
  }

  // 表格数据计算属性
  const tableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredDocuments.value.slice(start, end)
  })

  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
  }

  // 处理每页条数变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    if (currentPage.value > Math.ceil(total.value / pageSize.value)) {
      currentPage.value = 1
    }
  }

  // 更新列显示状态
  const changeColumn = (list: any) => {
    list.forEach((item: any, index: number) => {
      if (index < columns.length) {
        columns[index].show = item.show
      }
    })
  }

  // 导入本地 SVG 图标
  import wordIcon from '@/assets/svg/doc.svg'
  import pdfIcon from '@/assets/svg/pdf.svg'
  import markdownIcon from '@/assets/svg/md.svg'
  import txtIcon from '@/assets/svg/txt.svg'

  // 根据文件名获取文档图标
  const getDocumentIcon = (fileName: string) => {
    const extension = fileName.split('.').pop()?.toLowerCase() || ''

    switch (extension) {
      case 'doc':
      case 'docx':
        return wordIcon
      case 'pdf':
        return pdfIcon
      case 'md':
        return markdownIcon
      default:
        return txtIcon
    }
  }

  // 获取状态标签类型
  const getStatusTagType = (status: string) => {
    switch (status) {
      case STATUS.UPLOADING:
      case STATUS.GENERATING:
        return 'warning'
      case STATUS.UPLOAD_SUCCESS:
      case STATUS.GENERATE_SUCCESS:
        return 'success'
      case STATUS.UPLOAD_FAILED:
      case STATUS.GENERATE_FAILED:
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取状态文本
  const getStatusText = (status: string) => {
    return statusOptions.find((option) => option.value === status)?.label || '未知状态'
  }

  // 文档操作函数
  const previewDocument = (document: DocumentItem) => {
    currentDocument.value = document
    previewDialogVisible.value = true
  }

  const handleClosePreview = () => {
    previewDialogVisible.value = false
    currentDocument.value = null
  }

  const downloadDocument = (document: DocumentItem) => {
    ElMessage.success(`正在下载文档: ${document.fileName}`)
  }

  const deleteDocument = (document: DocumentItem) => {
    ElMessageBox.confirm(`确定要删除文档 "${document.fileName}" 吗？`, '删除文档', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        const index = allDocuments.value.findIndex((item) => item.id === document.id)
        if (index !== -1) {
          allDocuments.value.splice(index, 1)

          const filteredIndex = filteredDocuments.value.findIndex((item) => item.id === document.id)
          if (filteredIndex !== -1) {
            filteredDocuments.value.splice(filteredIndex, 1)
          }

          total.value = filteredDocuments.value.length

          // 处理页码
          const maxPage = Math.ceil(total.value / pageSize.value)
          if (
            tableData.value.length === 0 &&
            currentPage.value > 1 &&
            currentPage.value > maxPage
          ) {
            currentPage.value = Math.max(1, currentPage.value - 1)
          }

          ElMessage.success('文档删除成功')
        } else {
          ElMessage.error('未找到要删除的文档')
        }
      })
      .catch(() => {
        // 取消删除，不做任何操作
      })
  }

  // 日期和时间格式化函数
  const formatDate = (dateTimeString: string) => {
    return dateTimeString?.split(' ')[0] || ''
  }

  const formatTime = (dateTimeString: string) => {
    return dateTimeString?.split(' ')[1] || ''
  }

  // 上传文档相关函数
  const openUploadDialog = () => {
    uploadDialogVisible.value = true
    clearFileList()
  }

  const handleCloseUpload = () => {
    uploadDialogVisible.value = false
    clearFileList()
  }

  // 修复 handleUploadSuccess 函数
  const handleUploadSuccess = (file: UploadFile) => {
    const newDoc: DocumentItem = {
      id: (allDocuments.value.length + 1).toString(),
      fileName: file.name,
      uploader: '当前用户',
      status: STATUS.UPLOAD_SUCCESS,
      createTime: formatDateTime(new Date()),
      updateTime: formatDateTime(new Date()),
      previewUrl: null
    }

    allDocuments.value.unshift(newDoc)

    if (!searchForm.name && !searchForm.status) {
      filteredDocuments.value = allDocuments.value
    }

    total.value = filteredDocuments.value.length
  }

  // 修改 submitUpload 函数中调用 handleUploadSuccess 的方式
  const submitUpload = () => {
    if (fileList.value.length === 0) {
      ElMessage.warning('请选择要上传的文件')
      return
    }

    const validFiles = fileList.value.filter((file) => file.status !== 'removed')

    if (validFiles.length === 0) {
      ElMessage.warning('请选择要上传的文件')
      return
    }

    // 验证所有文件
    for (const file of validFiles) {
      if (!beforeUpload(file)) {
        return
      }
    }

    // 上传所有有效文件
    validFiles.forEach((file) => {
      ElMessage.info(`开始上传: ${file.name}`)

      // 模拟上传成功后的处理
      setTimeout(() => {
        handleUploadSuccess(file)
      }, 1000)
    })

    uploadDialogVisible.value = false
    clearFileList()
  }
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;

    .document {
      .doc-icon {
        width: 40px;
        height: 40px;
      }

      > div {
        margin-left: 10px;

        .doc-name {
          font-weight: 500;
          color: var(--el-color-primary);
          cursor: pointer;
        }

        .uploader {
          font-size: 12px;
          color: var(--art-text-gray-500);
        }
      }
    }

    .time-column {
      display: flex;
      flex-direction: column;

      .date {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }

      .time {
        margin-top: 4px;
        font-size: 12px;
        color: var(--art-text-gray-500);
      }
    }

    .custom-icon-button {
      margin-right: 5px;
    }

    .custom-icon {
      font-family: 'Material Icons', sans-serif;
      font-size: 16px;
      font-style: normal;
    }

    .document-preview {
      width: 100%;
      min-height: 600px;

      .no-preview {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 600px;

        .el-icon {
          margin-bottom: 20px;
          font-size: 48px;
          color: var(--el-color-warning);
        }

        p {
          font-size: 16px;
          color: var(--art-text-gray-600);
        }
      }
    }

    .upload-container {
      padding: 20px;

      .upload-form {
        .form-item {
          display: flex;
          align-items: flex-start;
          margin-bottom: 20px;

          .required-label {
            width: 80px;
            margin-right: 12px;
            line-height: 32px;
            text-align: right;

            &::before {
              margin-right: 4px;
              color: #f56c6c;
              content: '*';
            }
          }

          .upload-area {
            flex: 1;

            :deep(.el-upload-dragger) {
              width: 100%;
              max-width: 400px;
              height: auto;
            }

            .upload-content {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 20px 0;

              .upload-icon {
                margin-bottom: 12px;
                font-size: 36px;
                color: #409eff;
              }

              .upload-text {
                font-size: 14px;
                color: #606266;
                text-align: center;

                p:first-child {
                  margin-bottom: 6px;
                }
              }
            }
          }
        }
      }
    }

    .dialog-footer {
      text-align: right;
    }
  }
</style>
